/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package swym.client;

import java.io.*;
import swym.server.file.*;
/**
 *
 * @author henryja
 */
public class FileChunkWriter extends Thread
{
    private File file;
    private String folderPath;
    
    public FileChunkWriter(File file, String folderPath)
    {
        this.file = file;
        this.folderPath = folderPath;
    }
            
    public void run()
    {
        try
	{
		int numRead;
                int offset = 0;
		InputStream fis =  new FileInputStream(file);
		byte[] tempBuf = new byte[FileChunk.DEFAULT_SIZE];
		File tempFile = new File("temp/" + folderPath + "~");
                tempFile.mkdirs();
                File finishedFile = new File("temp/" + folderPath);
                
		do
		{
			numRead = fis.read(tempBuf);
			if (numRead >= 0)
  			{
                                File out  = new File(tempFile , offset+"");
                                out.createNewFile();
                                FileChunk chunk = new FileChunk( offset, tempBuf );
                                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(out));
                                oos.writeObject(chunk);
                                oos.close();
                                tempFile.renameTo(finishedFile);
			}
                        offset++;
		}
		while (numRead != -1);

                fis.close();  			
	}
	catch(FileNotFoundException fnfe)
	{
		fnfe.printStackTrace();
	}
	catch(IOException ioe)
	{
		ioe.printStackTrace();
        }
    }
}
